package com.hnyc.shopee;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;

/**
 * @auther zero
 * @date 2023/3/19
 **/
public class ShopeeUtils {
    public static long timest(){
        return System.currentTimeMillis() / 1000L;
    }
//    Shop APIs: partner_id, api path, timestamp, access_token, shop_id
//
//    Merchant APIs: partner_id, api path, timestamp, access_token, merchant_id
//
//    Public APIs: partner_id, api path, timestamp
    public static String shopSign(String path, long timest, long partnerId,String accessToken,long shopId, String partnerKey){

        return bizSign(path,timest,partnerId,accessToken,shopId,partnerKey);
    }
    public static String merchantSign(String path, long timest, long partnerId,String accessToken,long merchantId, String partnerKey){

        return bizSign(path,timest,partnerId,accessToken,merchantId,partnerKey);
    }
    public static String bizSign(String path, long timest, long partnerId,String accessToken,long id, String partnerKey){
        String tmp_base_string = String.format("%s%s%s%s%s", partnerId, path, timest,accessToken,id);
        byte[] partner_key;
        byte[] base_string;

        try {
            base_string = tmp_base_string.getBytes("UTF-8");
            partner_key =  partnerKey.getBytes("UTF-8");
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(partner_key, "HmacSHA256");
            mac.init(secret_key);
            return String.format("%032x",new BigInteger(1,mac.doFinal(base_string)));
        } catch (Exception e) {
            throw new RuntimeException(" 生成签名失败");
        }
    }
}
